package com.itheima.reggie.commom;

/*
@date 2022年07月29日19:44
*/

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.Message;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException exception) {
        log.error("接收到异常,{}", exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String name= split[2] + "已存在";
            return R.error(name);
        }
        return R.error("未知异常");
    }

    /**
     * 异常处理仿佛1,捕获自定义异常
     * @param exception
     * @return
     */
   @ExceptionHandler(CustomException.class)
    public  R<String> exceptionHander(CustomException exception){
       String message = exception.getMessage();
       return R.error(message);
    }

}